package mypi;

import java.io.DataOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;

import comm.ClientPriority;

import client.Client;

public class PiClient extends Client {


	private static final int SCALE = 5000;
	private static final int WORK_SIZE = 100;


	// 10000 . 2000
	public PiClient(ClientPriority priority, int problemNumber, int version,
			String masterAddress, int masterPort, String codeServerAddress,
			int codeServerPort) {
		super(priority, problemNumber, version, masterAddress, masterPort,
				codeServerAddress, codeServerPort);
		// TODO Auto-generated constructor stub
	}


	public void execute() {
		long time = System.currentTimeMillis();
		BigDecimal result = new BigDecimal("0");
		result = result.setScale(SCALE);
		int numIterations = SCALE / WORK_SIZE;
		for (int i = 0; i < numIterations; i++) {
			System.out.println("1: create tasks");
			PiTask piCalc = new PiTask(i, i * WORK_SIZE, (i + 1) * WORK_SIZE,
					SCALE);// (i+1)*WORK_SIZE+10);
			commit(piCalc);
			
		}
		//startWork();
		
		for (int i = 0; i < numIterations; i++) {
			System.out.println("aqui");
			result = result.add(((MyResult) (getNextResult())).getValue());

		}
		System.out.println(result);
		long end = System.currentTimeMillis();
		System.out.println("Time: " + (System.currentTimeMillis() - time));
		doLogTask("Pi.log", "Demorou: " + (end - time) + " SCALE: " + SCALE
				+ " WORKSIZE: " + WORK_SIZE + "\n");

	}

	private void doLogTask(String filename, String taskinfo) {
		FileOutputStream file;
		try {
			file = new FileOutputStream(filename, true);
			DataOutputStream out = new DataOutputStream(file);
			out.writeBytes(taskinfo);
			out.flush();
			out.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public static void main(String[] args) {
		new PiClient(ClientPriority.HIGH, 4, 4, "127.0.0.1", 0, "127.0.0.1", 0).execute();
	}

}
